﻿using Phones.Client.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace Phones.Client.Repository
{
    public class UnitOfWork<T> : IDisposable 
        where T : System.Data.Objects.DataClasses.EntityObject
    {
        public UnitOfWork() { Context = DataLayerStatics.NewContext(); }

        public PhonesEntities Context { get; private set; }

        public int Update(T entity)
        {
            Context.Attach(entity);
            Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
            return Context.SaveChanges();
        }

        public int Insert(T entity)
        {
            var set = Context.CreateObjectSet<T>();
            set.AddObject(entity);
            //Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Added);
            return Context.SaveChanges();
        }

        public int Delete(T entity)
        {
            var set = Context.CreateObjectSet<T>();
            set.Attach(entity);
            //Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Unchanged);
            set.DeleteObject(entity);
            return Context.SaveChanges();
        }

        public void Restore(T entity)
        {
            Context.Attach(entity);
            Context.Refresh(RefreshMode.StoreWins, entity);
        }

        public void Dispose()
        {
            if (Context != null)
            {
                Context.Dispose();
                Context = null;
            }
        }
    }
}
